$(function () {
    layui.use(['laydate','laytpl', 'table','form','formSelects','layer','util', 'soulTable'], function () {
        var laydate = layui.laydate,
            laytpl = layui.laytpl,
            table = layui.table,
            form = layui.form,
            formSelects = layui.formSelects,
            layer = layui.layer,
            util = layui.util,
            soulTable = layui.soulTable;
        var areaArr = [], allMeters = [], tbIndex = null;
        var devType = '0';

        initAll();
        function initAll(){


            form.val('search',{
                deviceTypeCode: devType
            });
            initDate();
            getAllAreas();
        }
        function initDate(){
            var max = util.toDateString(new Date(), 'yyyy-MM-dd HH:mm:ss');
            var cur = util.toDateString(new Date(), 'yyyy-MM-dd 00');
            var startDate = laydate.render({
                elem: '#startTime'
                ,value: cur
                , format: 'yyyy-MM-dd HH',
                ready: function(date){
                    $(".layui-laydate .layui-laydate-footer").on("click", "span.laydate-btns-time", function () {
                        var hourLi = $('.laydate-time-show .laydate-time-list > li:nth-child(1)');
                        hourLi.nextAll().remove();
                        $('.laydate-time-show .laydate-time-list > li').css('width','100%');
                        $('.laydate-time-show .laydate-time-list ol li').css({
                            'width':'100%',
                            'text-align': 'center',
                            'padding': 0,
                        });
                    });
                }
                , max: max
                , type: 'datetime'
                , done: function(value, date, endDate){
                    $(".refreshBtn").click();
                }
            });
            var endDate = laydate.render({
                elem: '#endTime'
                ,value: new Date()
                , format: 'yyyy-MM-dd HH',
                ready: function(date){
                    $(".layui-laydate .layui-laydate-footer").on("click", "span.laydate-btns-time", function () {
                        var hourLi = $('.laydate-time-show .laydate-time-list > li:nth-child(1)');
                        hourLi.nextAll().remove();
                        $('.laydate-time-show .laydate-time-list > li').css('width','100%');
                        $('.laydate-time-show .laydate-time-list ol li').css({
                            'width':'100%',
                            'text-align': 'center',
                            'padding': 0,
                        });
                    });
                }
                , max: max
                , type: 'datetime'
                , done: function(value, date, endDate){
                    $(".refreshBtn").click();
                }
            });
        }

        function getAllAreas(){
            $.ajax({
                type: "GET",
                url: ctx + "/areaManger/areaAll.do",
                dataType: "json",
                success: function (result) {
                    if (result != null) {
                        var getTpl = $('#area-tpl').html();
                        laytpl(getTpl).render(result, function(html){
                            $('.areaMenu').html(html);
                            formSelects.render('areaMenu');
                            formSelects.btns('areaMenu', ['select', 'remove','reverse'], {show: 'name', space: '10px'});
                            formSelects.value('areaMenu', 'val');
                            var initarea = result.map(function(item){
                                return item.areaId
                            });
                            formSelects.value('areaMenu', initarea);
                            areaArr.length = 0;
                            areaArr =  JSON.parse(JSON.stringify(result));
                            // filterMeters(areaArr);
                            getAllMeters();
                        });
                    }
                }
            });
        }

        function getAllMeters(){
            $.ajax({
                type: "GET",
                url: ctx + "/report/getAllMeters.do",
                data: {
                    deviceTypeCode: devType
                },
                dataType: "json",
                success: function (result) {
                    if (result != null) {
                        allMeters = result.sort(compare('areaId'));
                        // getAllAreas();
                        filterMeters(areaArr);
                    }
                }
            });
        }

        function filterMeters(areaArr) {
            var list = [], meters = [], typeMeter = [];
            allMeters.forEach(function(item){
                areaArr.forEach(function(val){
                    if(item.areaId == val.areaId){
                        typeMeter.push(item);
                        // list.push({"name": val.areaName, "type": "optgroup"});
                        // list.push({"name": item.deviceName + '_' + item.anotherName, "value": item.meterCode});
                    }
                });
            });
            let typeMeterArr = typeMeter.filter(function (val) {
                return val.deviceTypeCode == devType
            });
            typeMeterArr.forEach(function (ite) {
                meters.push(ite.meterCode);
                list.push({"name": ite.areaName, "type": "optgroup"});
                list.push({"name": ite.anotherName, "value": ite.meterCode});
            });
            formSelects.data('select-meter', 'local', {
                arr: uniqObjInArray(list)
            });
            formSelects.btns('select-meter', ['select', 'remove','reverse'], {show: 'name', space: '10px'});
            formSelects.value('select-meter', 'val');
            formSelects.value('select-meter', meters);
            $(".refreshBtn").click();
        }

        // 监听区域多选
        formSelects.on('areaMenu', function(id, vals, val, isAdd, isDisabled){
            areaArr.length = 0;
            vals.forEach(function(item){
                areaArr.push({"areaId" :item.value, "areaName" : item.name});
            });
            filterMeters(areaArr);
        }, true);

        form.on('select(typeMenu)', function (data) {
            devType = data.value;
            getAllMeters();
        });

        // 监听设备多选
        formSelects.on('select-meter', function(id, vals, val, isAdd, isDisabled){
            $(".refreshBtn").click();
        }, true);

        //判断权限
        function hasAuth(authCode) {
            var authArray=authStr.split(",");
            if(authArray&&authArray.length>0){
                for(var i=0;i<authArray.length;i++){
                    if(authArray[i].trim()==authCode){
                        return true;
                    }
                }
            }
            return false;
        }

        //点击刷新
        $('.searchBtn').click(function(){
            $(".refreshBtn").click();
        });
        $(".refreshBtn").click(function () {
            form.on('submit(search)', function(data){
                console.log(data.field)
                getDatas(data.field);
                return false;
            });
        });

        function getDatas(datas) {
            // console.log(datas);
            $.ajax({
                type: "POST",
                url: ctx + "/detailData/queryAll.do",
                data: datas,
                dataType: "json",
                success: function (result) {
                    if (result.code == "000000") {
                        renderTable(result.data);
                    }
                }
            });
        }

        //勾选的水表表格
        function renderTable(data) {
            var tbHeigth = $('.main-part').height();
            tbIndex = table.render({
                elem: '#reports'
                , id: 'myTable'
                , data: data
                ,heigth: tbHeigth
                , drag: false
                , title: '详细数据记录'
                , cols: [[
                    {field: 'detailDate', title: '时间', templet: '<div>{{ d.detailDate }}时</div>'}
                    , {field: 'anotherName', title: '设备位置'}
                    , {field: 'standard', title: '标准用量(T)'}
                    , {field: 'intervalQuantity', title: '实际用量(T)'}
                    , {field: 'currentQuantiry', title: '表盘读数'}
                    , {field: 'isOver', title: '是否超标'}
                    , {field: 'descrition', title: '备注'}
                ]]
                , page: {
                        layout: ['prev', 'page', 'next', 'count', 'skip', 'limit']
                        , groups: 5 //只显示 5 个连续页码
                        , limit: 15  //每页显示条数
                        , limits: [15, 30, 45, 60]
                    }
                , totalRow: false
                , loading: true
                , done:function(res, curr, count){
                    $('.layui-table-view > .layui-table-box').height(tbHeigth - 41);
                    $('.layui-table-view > .layui-table-box .layui-table-body').height(tbHeigth - 80);
                    soulTable.render(this);
                }
            });
        }

        // 导出excel
        $('.exportBtn').click(function () {
            soulTable.export('myTable', {filename: '详细数据记录.xlsx'});
        });

        // 打印
        $('.printBtn').click(function () {
            createPrintTable();
            // 创建iframe，填入需要打印的内容和样式
            var iframe = document.createElement('IFRAME'),
                doc = null,
                style = ["<style>", "body{font-size: 12px; color: #000;}",
                    "table{width: 100%; border-collapse: collapse; border-spacing: 0;}",
                    "th,td{line-height: 20px; padding: 5px 0; border: 1px solid #000; text-align: center; font-size: 12px; color: #000;}",
                    "thead tr th:first-child,tbody tr td:first-child{width:80px}",
                    "a{color: #000; text-decoration:none;}", "*.layui-hide{display: none}", ".ptitle{font-size:16px;font-weight:bold;text-align:center;}" ,"</style>"].join(""),
                printHtml = $($('#printContentBox .layui-table-view > .layui-table-box > .layui-table-header').html()),
                ptitle = $('<div class="ptitle">' + $('#printcontent .title').text() + '</div>');
            iframe.setAttribute("id", "print-iframe");
            iframe.setAttribute('style', 'position:absolute;width:100%;height:100%;left:0px;top:0px;z-index:1024;background-color:#fff;');
            document.body.appendChild(iframe);
            doc = iframe.contentWindow.document;
            printHtml.append($('#printContentBox .layui-table-view > .layui-table-box > .layui-table-main').find("table").html());
            printHtml.find("th.layui-table-patch").remove();
            printHtml.find(".layui-table-col-special").remove();
            doc.write(style + ptitle.prop("outerHTML") +printHtml.prop("outerHTML"));
            iframe.contentWindow.focus();
            iframe.contentWindow.print();
            iframe.remove();
            $('#printContentBox').empty();
        });

        function createPrintTable() {
            $('#printContentBox').html('<table id="printTb"></table>');
            var temp = tbIndex.config;
            // 所有数据加载为新表格
            table.render({
                elem: '#printTb'
                , data: temp.data
                , cellMinWidth: 48
                , size: 'sm'
                , defaultToolbar: []
                , cols: temp.cols
                , limit: temp.data.length
            })
        }
    });
});
